﻿using AutoMapper.Internal.Mappers;
using rbac.contracts.Dto.Output;
using rbac.contracts.Interface;
using rbac.domain.Interface;
using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using rbac.contracts.Dto.Input;

namespace rbac.services
{//123456 asfasfsafas
    public class UserService : ServiceBase, IUserService
    {
        private readonly IUserRepository _userRepository;
       
        private readonly IUserRoleRepository _userRoleRepository;
        private readonly IRoleRepository _roleRepository;

        public UserService(IUserRepository userRepository
            , IUserRoleRepository userRoleRepository
            , IRoleRepository roleRepository)
        {
            _userRepository = userRepository;
            _userRoleRepository = userRoleRepository;
            _roleRepository = roleRepository;
        }
        /// <summary>
        /// 哈哈哈发发发通天塔快快快
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public PageOutput<UserOutput> GetUsers(GetUsersInput input)
        {
            // 拿到所有的用户的信息11111（）
            // select * from users;
            var query = _userRepository.GetUsers().Where(p=>p.IsDeleted==false)
                .AsNoTracking();
            if (!string.IsNullOrWhiteSpace(input.UserName))
            {
                // 如果我们在UserName上面建立了索引，那最好使用StartWith
                // select Id,UserName from Users where UserName like '张%'
                query = query.Where(p => p.UserName!.StartsWith(input.UserName));
            }

            if (!string.IsNullOrWhiteSpace(input.Email))
            {
                // select Id,UserName from Users where UserName like '张%'
                // and Email like '%2526@qq.com%'
                query = query.Where(p => p.Email!.Contains(input.Email));
            }

            // 创建分页对象
            var result = new PageOutput<UserOutput>()
            {
                Total = query.Count(),
                PageSize = input.PageSize
            };
            
            // 分页
            var list = query.OrderBy(p => p.Id).Skip((input.PageIndex - 1) * input.PageSize)
                .Take(input.PageSize).ToList();
            // 用户ID集合
            var userIdList = list.Select(p => p.Id);
            
            
            
            // 根据用户Id查询角色
            // select UserId,RoleName,RoleId from userrole a
            // join role b on a.RoleId=b.id where userid in(1,,3,,45)
            var roleList = (from ur in _userRoleRepository.UserRoles()
                join r in _roleRepository.Roles()
                    on ur.RoleId equals r.Id
                where userIdList.Contains(ur.UserId)
                select new
                {
                    ur.UserId,
                    r.RoleName,
                    r.Id
                }).ToList();

            // 分组
            /**
             * 1. 张三   ==》 管理员 ，客户
             * 2. 李四    ==> 管理员，普通用户
             */
            var roleGroup = roleList.GroupBy(p => p.UserId);
            result.Data = _mapper.Map<List<UserOutput>>(list);
            foreach (var g in roleGroup)
            {
                // 找到这个用户
                var user = result.Data.FirstOrDefault(p => p.Id == g.Key);
                user.Roles = g.ToList().Select(r => new RoleOutput
                {
                    Id = r.Id,
                    RoleName = r.RoleName
                }).ToList();
            }

            return result;
        }

        public UserOutput Login(LoginInput input)
        {
            //登录
            var userInfo = _userRepository.Login(input.UserName, input.Pwd);
            var DTO = _mapper.Map<UserOutput>(userInfo);

            if (DTO is not null)
            {
                DTO.Roles = _mapper.Map<List<RoleOutput>>(_userRoleRepository.GetRolesByUserId(userInfo.Id));
            }
            return DTO;
        }
    }
}
